package com.gosuncn.utils;

import com.aspose.words.Document;
import com.aspose.words.License;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;


import java.io.*;

/**
 * @Author
 * @Date 2022/1/12 17:07
 * @类说明 aspose实现word转pdf
 */
public class PdfUtil {

    private static final Logger log = LoggerFactory.getLogger(PdfUtil.class);


    /**
     * @Description: 去水印
     * @param:
     * @return:
    */
    private static boolean getLicense() {
        boolean result = false;
        try {
            //  license.xml应放在..\WebRoot\WEB-INF\classes路径下
            InputStream is = PdfUtil.class.getClassLoader().getResourceAsStream("license.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @Description: word转pdf
     * @param:
     * @return:
    */
    public static void doc2pdf(InputStream in, OutputStream out) {
        if (!getLicense()) {          // 验证License 若不验证则转化出的pdf文档会有水印产生
            log.error("doc2pdf,解析水印失败，请重试");
            return;
        }
        try {
            long old = System.currentTimeMillis();
            //Address是将要被转化的word文档
            Document doc = new Document(in);
            //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
            doc.save(out, com.aspose.words.SaveFormat.PDF);
            long now = System.currentTimeMillis();
            System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒");  //转化用时
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        ResourcePatternResolver b = new PathMatchingResourcePatternResolver();
        try {
            Resource[] resources = b.getResources("classpath*:model.xml");
            InputStream inputStream = resources[0].getInputStream();

            Document doc = new Document(new FileInputStream("C:\\Users\\zhangxiaolong\\Desktop/temp.xml"));

        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(PdfUtil.class.getProtectionDomain().getCodeSource().getLocation());// 获取程序的根目录
//		 excel2pdf("E:\\personalTax.xls","E:\\personalTax.pdf");
        //输出pdf文件

        //保存PDf结果文件到E:/20201219111.pdf
        //document.saveToFile("D:\\\\安装软件\\\\谷歌浏览器下载\\\\报警回执4444.pdf", com.spire.doc.FileFormat.PDF);
    }

}
